﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Interactivity;
using System.Windows.Controls;
using System.Windows;

namespace XWord.WPF.Behaviors
{
    public class ScrollAutoBehavior : Behavior<ListBox>
    {
        protected override void OnAttached()
        {
            base.OnAttached();
            AssociatedObject.AddHandler(ScrollViewer.ScrollChangedEvent, new ScrollChangedEventHandler(ScrollChanged));
        }

        private double itemHeight;
        private void ScrollChanged(object sender, ScrollChangedEventArgs e)
        {
            //var element = e.OriginalSource as ScrollViewer;
            //if (!AssociatedObject.HasItems) return;
            //if (itemHeight <= 0)
            //{
            //    var item = AssociatedObject.ItemContainerGenerator.ContainerFromIndex(Convert.ToInt32(e.VerticalOffset)) as FrameworkElement;
            //    itemHeight = item.ActualHeight;
            //}

            //var count = Convert.ToInt32(AssociatedObject.ActualHeight / itemHeight);
            //if (count > AssociatedObject.Items.Count)
            //    element.ScrollToVerticalOffset(0);
            //else

            //    if (AssociatedObject.Items.Count < e.VerticalOffset)
            //    {
            //        element.ScrollToVerticalOffset(AssociatedObject.Items.Count - count);

            //    }
            //var count = Convert.ToInt32(AssociatedObject.ActualHeight / item.ActualHeight);
            //var displayItem = Convert.ToInt32((e.VerticalOffset + Math.Ceiling(e.VerticalOffset * (count - 2) / (AssociatedObject.Items.Count - count + 1))));
           
        }
    }
}
